package com.exp.bookhouse.controller;

import com.exp.bookhouse.pojo.myUser;
import com.exp.bookhouse.pojo.vo.UserVo;
import com.exp.bookhouse.service.UserService;
import com.exp.bookhouse.util.ApiJSONResult;
import com.exp.bookhouse.util.RedisUtil;
import com.exp.bookhouse.util.UploadService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Api(value = "用户接口",tags = "用户操作")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${nginx.port}")
    private String port;

    @Value("${nginx.host}")
    private String host;

    @Value("${nginx.group}")
    private String group;

    /**
     * 用户登录
     * paramType:
     * header：请求参数放置于Request Header，使用@RequestHeader获取
     * query：请求参数放置于请求地址，使用@RequestParam获取
     * path：（用于restful接口）-->请求参数的获取：@PathVariable
     *
     * @param encryptedData 明文,加密数据
     * @param iv            加密算法的初始向量
     * @param code          用户允许登录后，回调内容会带上 code（有效期五分钟），开发者需要将 code 发送到开发者服务器后台，
     *                      使用code 换取 session_key api，将 code 换成 openid 和 session_key
     * @return 用户信息
     */
    @ApiOperation(value = "微信登录", notes = "微信用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "encryptedData", value = "明文", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "iv", value = "加密算法的初始向量", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "code", value = "临时登录凭证", required = true, dataType = "String")
    })
    @PostMapping(value = "/decodeUser")
    public ApiJSONResult weChatLogin(String encryptedData, String iv, String code) throws Exception {
        if (StringUtils.isBlank(encryptedData + iv + code)) {
            throw new Exception("参数不能为空");
        }
        myUser myUser = userService.weChatLogin(encryptedData, iv, code);
        String uniqueToken = UUID.randomUUID().toString();
        redisUtil.set("user_redis_session"+":"+ myUser.getId(),uniqueToken,1000*60*30); //1000*30分钟

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(myUser, userVo); //复制user 到 userVo中
        userVo.setUserToken(uniqueToken);
        return ApiJSONResult.ok(userVo);
    }


    /**
     * 用户更新
     * @param myUser 用户对象
     * @return 成功与否
     */
    @ApiOperation(value = "用户更新", notes = "用户更新")
    @PutMapping
    public ApiJSONResult updateUser(@ApiParam(value = "用户对象", required = true) @RequestBody myUser myUser) {
        int b = userService.updateUser(myUser);
        if (b == 1) {
            return ApiJSONResult.ok("更新成功");
        }else{
            return ApiJSONResult.errorMsg("更新失败");
        }
    }



    /**
     * 文件上传
     * @param file   上传的文件
     * @param userId 用户id
     * @return StorePath
     * @deprecated 文件上传
     * storePath
     * "group": "group1",
     * "path": "M00/00/01/wKj4RFvuZlOALpzMAAJZc0IRPSY16.jpg",
     * fullPath": "group1/M00/00/01/wKj4RFvuZlOALpzMAAJZc0IRPSY16.jpg"
     */
    @ApiOperation(value = "文件上传", notes = "根据用户id上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "headImage", value = "用户当前的头像url", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping(value = "/upload")
    public ApiJSONResult uploadFileAndUserId(@ApiParam(value = "上传的文件", required = true) MultipartFile file, Long userId, String headImage) throws Exception {
        /* 设置文件信息 */
        if (StringUtils.isBlank(userId.toString())) {
            throw new Exception("userId不能为空");
        }

        if (file == null) {
            throw new Exception("文件不能为空");
        }
//        http://images.server.com/bookstore/ac6eddc451da81cb6740cd585266d01608243184_20202214102253.jpg
        String path = uploadService.uploadFile(file);   //上传文件返回不带分组路径
        String fullUrl = "http://"+host+":"+port+"/"+path;   //全路径
        int count = userService.updateHeadImage(userId,fullUrl);    //保存数据库
        if(count == 0){
            throw new Exception("头像更新失败");
        }

        //删除服务器的图片
        if(headImage.contains(group)){
            String[] split = headImage.split(group+"/");
            uploadService.deleteFile(split[1]);
        }
        return ApiJSONResult.ok(fullUrl);
    }


}
